﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

namespace MingYuanYun.Primitives
{
    public static class DictionaryExtensions
    {
        public static T TryGetValue<T>(this IDictionary<string, T> dict, string key)
        {
            return dict.TryGetValue<string, T>(key);
        }

        public static TValue TryGetValue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
        {
            if (dict == null || key == null)
            {
                return default(TValue);
            }

            if (!dict.TryGetValue(key, out TValue value))
            {
                value = default(TValue);
            }

            return value;
        }

        public static T DicToObject<T>(this Dictionary<string, object> dict) where T : new()
        {
            var md = new T();
            CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
            TextInfo textInfo = cultureInfo.TextInfo;
            foreach (var d in dict)
            {
                var filed = textInfo.ToTitleCase(d.Key);
                try
                {
                    var value = d.Value;
                    md.GetType().GetProperty(filed).SetValue(md, value);
                }
                catch (Exception e)
                {

                }
            }
            return md;
        }
    }
}
